package com.indusfo.spc.service.impl;

import com.indusfo.spc.controller.MatStationController;
import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.*;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.MatFlowService;
import com.indusfo.spc.vo.HintMessage;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @Author: 熊冰
 * @Date: 2019/11/20 14:19
 */
@Service
public class MatFlowServiceImpl implements MatFlowService {
    // 声明日志的静态变量
    private static final Logger logger = LoggerFactory.getLogger(MatFlowServiceImpl.class);

    @Resource
    private MatFlowMapper matFlowMapper;


    @Resource
    private MatStationMapper matStationMapper;
    @Resource
    private MatDeteMapper matDeteMapper;
    @Resource
    private MatBomMapper matBomMapper;
    @Resource
    private MatBadphenoMapper matBadphenoMapper;

    @Resource
    private MatVerMapper matVerMapper;


    //查询
    @Override
    public JSONObject queryMatFlow(MatFlow matFlow) {
        try {
            if (matFlow.getMatVerId() == null) {
                throw new ModifyFailedException(HintMessage.MATVERID_NULL);
            }
            //获取页面的数据个数
            Integer pagesize = matFlow.getPagesize();
            //获取查询的页数
            Integer pageindex = matFlow.getPageindex();
            if (pagesize != null && pageindex != null) {
                matFlow.setIncept(pagesize * (pageindex - 1));
            }
            //执行查询操作
            List<MatFlow> matFlowList = matFlowMapper.queryMatFlow(matFlow);

            //如果页数和页面数量都不为空的情况下进行计数
            if (matFlowList.isEmpty()) {
                return JSONObject.oK(HintMessage.QUERY_NULL, matFlowList, 0);
            } else {
                Integer count = matFlowMapper.countMatFlow(matFlow);
                return JSONObject.oK(HintMessage.QUERY_SUCCESS, matFlowList, count);
            }

        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());

        }
    }

    //新增
    @Override
    public JSONObject insertMatFlow(MatFlow matFlow) {
        try {
            if (matFlow.getMatFlowId() != null) {
                throw new ModifyFailedException(HintMessage.INSERT_ID);
            }
            //初始化基础数据
            if (matFlow.getDataState() == null) {
                matFlow.setDataState(1);
            }
            //判重
            checkParam(matFlow);
            //执行新增操作
            Integer row = matFlowMapper.insertMatFlow(matFlow);
            if (row == 0) {
                throw new ModifyFailedException(HintMessage.INSERT_DEFEATED);
            }
            return JSONObject.oK(HintMessage.INSERT_SUCCESS);
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    //修改
    @Override
    public JSONObject updateMatFlow(MatFlow matFlow) {
        try {
            if (matFlow.getMatFlowId() == null) {
                throw new ParamsErrorException(HintMessage.UPDATE_ID);
            }
            //初始化基础数据
            if (matFlow.getDataState() == null) {
                matFlow.setDataState(1);
            }
            //判重
            checkParam(matFlow);
            //执行修改操作
            int row = matFlowMapper.updateMatFlow(matFlow);
            if (row == 0) {
                throw new ModifyFailedException(HintMessage.UPDATE_DEFEATED);
            }
            return JSONObject.oK(HintMessage.UPDATE_SUCCESS);
        } catch (GlobalException e) {//捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    //删除
    @Override
    public JSONObject deleteMatFlow(List<Integer> matFlowIds, Integer dataState) {
        try {
            //空值判断
            if (dataState == null) {
                throw new ParamsErrorException(HintMessage.DATASTATE_NULL);
            }
            if (matFlowIds == null) {
                throw new ParamsErrorException(HintMessage.LIST_NULL);
            }
            //记录异常信息
            String msg = "";
            switch (dataState) {
                case 1:
                    msg = HintMessage.START_VALUE;
                    break;
                case 2:
                    msg = HintMessage.DELETE_VALUE;
                    break;
                case 3:
                    msg = HintMessage.STOP_VALUE;
                    break;
                default:
                    throw new ParamsErrorException(HintMessage.VIOLATION_OPERATION);
            }
            //执行删除操作
            int row = matFlowMapper.deleteMatFlow(matFlowIds, dataState);
            //声明msg字符串，用来存抛出的异常
            if (row == 0) {
                msg = msg + HintMessage.DEFEATED_VALUE;
            } else {
                msg = msg + HintMessage.SUCCESS_VALUE;
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 级联删除工序流程关联的工位、采集参数、关键物料、不良现象
     */
    @Transactional
    @Override
    public JSONObject deleteCascadeMatFlow(List<Integer> matFlowIds, Integer dataState) {
        //空值判断
        if (dataState == null) {
            throw new ParamsErrorException(HintMessage.DATASTATE_NULL);
        }
        if (matFlowIds == null) {
            throw new ParamsErrorException(HintMessage.LIST_NULL);
        }
        //记录异常信息
        String msg = "";
        switch (dataState) {
            case 1:
                msg = HintMessage.START_VALUE;
                break;
            case 2:
                msg = HintMessage.DELETE_VALUE;
                break;
            case 3:
                msg = HintMessage.STOP_VALUE;
                break;
            default:
                throw new ParamsErrorException(HintMessage.VIOLATION_OPERATION);
        }

        //执行主表删除操作
        int row = matFlowMapper.deleteMatFlow(matFlowIds, dataState);

        //根据传入的matFlowIds查询对应的工位、采集参数、关键物料、不良现象集合
        for (Integer matFlowId : matFlowIds) {

            //级联执行工位删除
            List<MatStation> matStationList = matStationMapper.queryMatStationByMatFlowId(matFlowId);
            if (matStationList != null && !matStationList.isEmpty()) {
                for (MatStation matStation : matStationList) {
                    matStationMapper.deleteMatStationByMatStationId(matStation.getMatStationId(), dataState);
                }
            }

            //级联执行采集参数删除
            List<MatDete> matDeteList = matDeteMapper.queryMatDeteByMatFlowId(matFlowId);
            if (matDeteList != null && !matDeteList.isEmpty()) {
                for (MatDete matDete : matDeteList) {
                    matDeteMapper.deleteMatDeteByMatDeteId(matDete.getMatDeteId(), dataState);
                }
            }

            //级联执行关键物料删除
            List<MatBom> matBomList = matBomMapper.queryMatBomByMatFlowId(matFlowId);
            if (matBomList != null && !matBomList.isEmpty()) {
                for (MatBom matBom : matBomList) {
                    matBomMapper.deleteMatBomByMatBomId(matBom.getMatBomId(), dataState);
                }
            }

            //级联执行不良现象删除
            List<MatBadpheno> matBadphenoList = matBadphenoMapper.queryMatBadphenoByMatFlowId(matFlowId);
            if (matBadphenoList != null && !matBadphenoList.isEmpty()) {
                for (MatBadpheno matBadpheno : matBadphenoList) {
                    matBadphenoMapper.deleteMatBadphenoByMatBadphenoId(matBadpheno.getMatBadphenoId(), dataState);
                }
            }

        }

        //声明msg字符串，用来存抛出的异常
        if (row == 0) {
            msg = msg + HintMessage.DEFEATED_VALUE;
        } else {
            msg = msg + HintMessage.SUCCESS_VALUE;
        }
        return JSONObject.oK(msg);
    }


    /**
     * @Author 熊冰 保存物料流程工位
     * @Date 2019/11/25 9:38
     */
    @Override
    public JSONObject saveMatStation(MatFlow matFlow) {
        try {
            //判空
            if (matFlow == null) {
                throw new ParamsErrorException(HintMessage.DATA_NULL);
            }
            if (matFlow.getMatFlowId() == null) {
                throw new ParamsErrorException(HintMessage.MATFLOWID_NULL);
            }

            //获取流程id
            Integer matFlowId = matFlow.getMatFlowId();
            //获取list集合
            List<MatStation> matStationList = new ArrayList<>();
            matStationList = matFlow.getMatStationList();
            for (MatStation matStation : matStationList) {
                matStation.setMatFlowId(matFlowId);
            }

            //去除不要的工位
            //反查版本
            MatFlow matf=matFlowMapper.queryMatFlowByMatFlowId(matFlowId);
            List<MatFlow> matFlowList = matFlowMapper.queryMatFlowByMatVerId(matf.getMatVerId());
            List<MatFlow> matFlowList1 =new ArrayList<>();


            //提出相同工序
            if(matFlowList.size()!=0){
            for (MatFlow mf:matFlowList ) {
                if(matf.getProId().equals(mf.getProId())){
                    matFlowList1.add(mf);
                }
            }
            }
            matFlowList.removeAll(matFlowList1);
            //查询流程下所有工位
            String strStation="";
            List<MatStation> matStationList1 = matStationMapper.queryMatStationByMatFlowList(matFlowList);
            List<MatStation> matStationList2  =new ArrayList<>();
            for (MatStation station:matStationList1  ) {
                for (MatStation station1:matStationList ) {
                    if(station.getStationId().equals(station1.getStationId())){
                        matStationList2.add(station1);
                        strStation=strStation+station.getStationId()+" ";
                    }
                }

            }
            matStationList.removeAll(matStationList2);


            //获取数据库数据
            MatStation matStation1 = new MatStation();
            matStation1.setMatFlowId(matFlowId);
            List<MatStation> oldmatStationList = matStationMapper.queryMatStation(matStation1);
            //删除
            List<Integer> deleteList = new ArrayList<>();
            List<Integer> oldIds = new ArrayList<>();
            List<Integer> newIds = new ArrayList<>();
            if (oldmatStationList != null) {
                for (MatStation matStation : oldmatStationList
                ) {
                    oldIds.add(matStation.getMatStationId());
                }
            }
            if (matStationList != null) {
                for (MatStation matStation : matStationList
                ) {
                    newIds.add(matStation.getMatStationId());
                }
            }
            HashSet h1 = new HashSet(oldIds);
            HashSet h2 = new HashSet(newIds);
            h1.removeAll(h2);
            deleteList.addAll(h1);
            int deleterow = 0;
            int insertrow = 0;
            int updaterow = 0;
            if (deleteList.size() != 0) {
                deleterow = matStationMapper.deleteMatStation(deleteList, 2);
            }
            //删除完成  进行新增 和 修改
            if (matStationList != null) {
                for (MatStation matStation : matStationList
                ) {
                    if (matStation.getDataState() == null) {
                        matStation.setDataState(1);
                    }


                    if (matStation.getMatStationId() != null) {
                        if (matStation.getMatStationId().equals(0)) {
                            matStation.setMatStationId(null);
                            // 执行判重操作
                            Integer Counts = matStationMapper.checkMatStation(matStation);
                            if (Counts == 0) {
                                insertrow = insertrow + matStationMapper.insertMatStation(matStation);
                            }

                        } else {
                            // 执行判重操作
                            Integer Counts = matStationMapper.checkMatStation(matStation);
                            if (Counts == 0) {
                                updaterow = updaterow + matStationMapper.updateMatStation(matStation);
                            }

                        }
                    }
                }
            }
//            if(strStation.equals("")){
                return JSONObject.oK(HintMessage.SAVE_SUCCESS, deleterow + insertrow + updaterow);
//            }else{
//                return JSONObject.oK(strStation+HintMessage.INSERT_DEFEATED, deleterow + insertrow + updaterow);
//            }

        } catch (GlobalException e) {// 捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * @Author 熊冰 保存 物料流程采集项目
     * @Date 2019/11/25 9:38
     */
    @Override
    public JSONObject saveMatDete(MatFlow matFlow) {
        try {
            //判空
            if (matFlow == null) {
                throw new ParamsErrorException(HintMessage.DATA_NULL);
            }
            if (matFlow.getMatFlowId() == null) {
                throw new ParamsErrorException(HintMessage.MATFLOWID_NULL);
            }
            //获取流程id
            Integer matFlowId = matFlow.getMatFlowId();
            //获取list集合
            List<MatDete> matDeteList = new ArrayList<>();
            matDeteList = matFlow.getMatDeteList();
            for (MatDete matDete : matDeteList) {
                matDete.setMatFlowId(matFlowId);
            }


            //获取数据库数据
            MatDete matDete1 = new MatDete();
            matDete1.setMatFlowId(matFlowId);
            List<MatDete> oldmatDeteList = matDeteMapper.queryMatDete(matDete1);
            //删除
            List<Integer> deleteList = new ArrayList<>();
            List<Integer> oldIds = new ArrayList<>();
            List<Integer> newIds = new ArrayList<>();
            if (oldmatDeteList != null) {
                for (MatDete matDete : oldmatDeteList
                ) {
                    oldIds.add(matDete.getMatDeteId());
                }
            }
            if (matDeteList != null) {
                for (MatDete matDete : matDeteList
                ) {
                    newIds.add(matDete.getMatDeteId());
                }
            }
            HashSet h1 = new HashSet(oldIds);
            HashSet h2 = new HashSet(newIds);
            h1.removeAll(h2);
            deleteList.addAll(h1);
            int deleterow = 0;
            int insertrow = 0;
            int updaterow = 0;
            if (deleteList.size() != 0) {
                deleterow = matDeteMapper.deleteMatDete(deleteList, 2);
            }
            //删除完成  进行新增 和 修改
            if (matDeteList != null) {
                for (MatDete matDete : matDeteList
                ) {
                    if (matDete.getDataState() == null) {
                        matDete.setDataState(1);
                    }

                    if (matDete.getMatDeteId() != null) {
                        if (matDete.getMatDeteId().equals(0)) {
                            matDete.setMatDeteId(null);
                            Integer Counts = matDeteMapper.checkMatDete(matDete);
                            if (Counts == 0) {
                                insertrow = insertrow + matDeteMapper.insertMatDete(matDete);
                            }

                        } else {
                            Integer Counts = matDeteMapper.checkMatDete(matDete);
                            if (Counts == 0) {
                                updaterow = updaterow + matDeteMapper.updateMatDete(matDete);
                            }
                        }
                    }
                }
            }
            return JSONObject.oK(HintMessage.SAVE_SUCCESS, deleterow + insertrow + updaterow);
        } catch (GlobalException e) {// 捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * @Author 熊冰 保存物料流程关键物料
     * @Date 2019/11/25 9:38
     */
    @Override
    public JSONObject saveMatBom(MatFlow matFlow) {
        try {
            //判空
            if (matFlow == null) {
                throw new ParamsErrorException(HintMessage.DATA_NULL);
            }
            if (matFlow.getMatFlowId() == null) {
                throw new ParamsErrorException(HintMessage.MATFLOWID_NULL);
            }
            //获取流程id
            Integer matFlowId = matFlow.getMatFlowId();
            //获取list集合
            List<MatBom> matBomList = new ArrayList<>();
            matBomList = matFlow.getMatBomList();
            for (MatBom matBom : matBomList) {
                matBom.setMatFlowId(matFlowId);
            }


            //获取数据库数据
            MatBom matBom1 = new MatBom();
            matBom1.setMatFlowId(matFlowId);
            List<MatBom> oldmatBomList = matBomMapper.queryMatBom(matBom1);
            //删除
            List<Integer> deleteList = new ArrayList<>();
            List<Integer> oldIds = new ArrayList<>();
            List<Integer> newIds = new ArrayList<>();
            if (oldmatBomList != null) {
                for (MatBom matBom : oldmatBomList
                ) {
                    oldIds.add(matBom.getMatBomId());
                }
            }
            if (matBomList != null) {
                for (MatBom matBom : matBomList
                ) {
                    newIds.add(matBom.getMatBomId());
                }
            }
            HashSet h1 = new HashSet(oldIds);
            HashSet h2 = new HashSet(newIds);
            h1.removeAll(h2);
            deleteList.addAll(h1);
            int deleterow = 0;
            int insertrow = 0;
            int updaterow = 0;
            if (deleteList.size() != 0) {
                deleterow = matBomMapper.deleteMatBom(deleteList, 2);
            }
            //删除完成  进行新增 和 修改
            if (matBomList != null) {
                for (MatBom matBom : matBomList
                ) {
                    if (matBom.getDataState() == null) {
                        matBom.setDataState(1);
                    }


                    if (matBom.getMatBomId() != null) {
                        if (matBom.getMatBomId().equals(0)) {
                            matBom.setMatBomId(null);
                            // 执行判重操作
                            Integer Counts = matBomMapper.checkMatBom(matBom);
                            if (Counts == 0) {
                                insertrow = insertrow + matBomMapper.insertMatBom(matBom);
                            }

                        } else {
                            // 执行判重操作
                            Integer Counts = matBomMapper.checkMatBom(matBom);
                            if (Counts == 0) {
                                updaterow = updaterow + matBomMapper.updateMatBom(matBom);
                            }
                        }
                    }
                }
            }
            return JSONObject.oK(HintMessage.SAVE_SUCCESS, deleterow + insertrow + updaterow);
        } catch (GlobalException e) {// 捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * @Author 熊冰 保存 物料流程不良现象
     * @Date 2019/11/25 9:37
     */
    @Override
    public JSONObject saveMatBadpheno(MatFlow matFlow) {
        try {
            //判空
            if (matFlow == null) {
                throw new ParamsErrorException(HintMessage.DATA_NULL);
            }
            if (matFlow.getMatFlowId() == null) {
                throw new ParamsErrorException(HintMessage.MATFLOWID_NULL);
            }
            //获取流程id
            Integer matFlowId = matFlow.getMatFlowId();

            //获取list集合
            List<MatBadpheno> matBadphenoList = new ArrayList<>();
            matBadphenoList = matFlow.getMatBadphenoList();
            for (MatBadpheno matBadpheno : matBadphenoList) {
                matBadpheno.setMatFlowId(matFlowId);
            }

            //获取数据库数据
            MatBadpheno matBadpheno1 = new MatBadpheno();
            matBadpheno1.setMatFlowId(matFlowId);
            List<MatBadpheno> oldmatBadphenoList = matBadphenoMapper.queryMatBadpheno(matBadpheno1);
            //删除
            List<Integer> deleteList = new ArrayList<>();
            List<Integer> oldIds = new ArrayList<>();
            List<Integer> newIds = new ArrayList<>();
            if (oldmatBadphenoList != null) {
                for (MatBadpheno matBadpheno : oldmatBadphenoList
                ) {
                    oldIds.add(matBadpheno.getMatBadphenoId());
                }
            }
            if (matBadphenoList != null) {
                for (MatBadpheno matBadpheno : matBadphenoList
                ) {
                    newIds.add(matBadpheno.getMatBadphenoId());
                }
            }
            HashSet h1 = new HashSet(oldIds);
            HashSet h2 = new HashSet(newIds);
            h1.removeAll(h2);
            deleteList.addAll(h1);
            int deleterow = 0;
            int insertrow = 0;
            int updaterow = 0;
            if (deleteList.size() != 0) {
                deleterow = matBadphenoMapper.deleteMatBadpheno(deleteList, 2);
            }
            //删除完成  进行新增 和 修改
            if (matBadphenoList != null) {
                for (MatBadpheno matBadpheno : matBadphenoList
                ) {
                    if (matBadpheno.getDataState() == null) {
                        matBadpheno.setDataState(1);
                    }


                    if (matBadpheno.getMatBadphenoId() != null) {
                        if (matBadpheno.getMatBadphenoId().equals(0)) {
                            matBadpheno.setMatBadphenoId(null);
                            // 执行判重操作
                            Integer Counts = matBadphenoMapper.checkMatBadpheno(matBadpheno);
                            if (Counts == 0) {
                                insertrow = insertrow + matBadphenoMapper.insertMatBadpheno(matBadpheno);
                            }

                        } else {
                            // 执行判重操作
                            Integer Counts = matBadphenoMapper.checkMatBadpheno(matBadpheno);
                            if (Counts == 0) {
                                updaterow = updaterow + matBadphenoMapper.updateMatBadpheno(matBadpheno);
                            }
                        }
                    }
                }
            }
            return JSONObject.oK(HintMessage.SAVE_SUCCESS, deleterow + insertrow + updaterow);
        } catch (GlobalException e) {// 捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    //判重
    public void checkParam(MatFlow matFlow) {

        Integer matVerId = matFlow.getMatVerId();
        Integer proId = matFlow.getProId();
        Integer sequence = matFlow.getSequence();
        Integer serialNum = matFlow.getSerialNum();
        //判空
        if (matVerId == null) {
            throw new ParamsErrorException(HintMessage.MATVERID_NULL);
        }
        if (proId == null) {
            throw new ParamsErrorException(HintMessage.PROID_NULL);
        }
        if (sequence == null) {
            throw new ParamsErrorException(HintMessage.SEQUENCE_NULL);
        }
        if (serialNum == null) {
            throw new ParamsErrorException(HintMessage.SERIALNUM_NULL);
        }
        //判断字符长度


        // 执行判重操作
        Integer Counts = matFlowMapper.checkMatFlow(matFlow);
        if (Counts != 0) {
            throw new ParamsErrorException(HintMessage.REPEATING_DATA);
        }

    }

    /**
     * 去添加查询（产品，任务单，批次）
     */
    @Override
    public JSONObject queryListMatFlowToInsert(MatFlow matFlow) {
        try {
            //获取页面的数据个数
            Integer pagesize = matFlow.getPagesize();
            //获取查询的页数
            Integer pageindex = matFlow.getPageindex();
            if (pagesize != null && pageindex != null) {
                matFlow.setIncept(pagesize * (pageindex - 1));
            }
            //执行查询操作
            List<MatFlow> matFlowList = matFlowMapper.queryMatFlowToInsert(matFlow);

            //如果页数和页面数量都不为空的情况下进行计数
            if (matFlowList.isEmpty()) {
                return JSONObject.oK(HintMessage.QUERY_NULL, matFlowList, 0);
            } else {
                Integer count = matFlowMapper.countMatFlowToInsert(matFlow);
                return JSONObject.oK(HintMessage.QUERY_SUCCESS, matFlowList, count);
            }

        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());

        }
    }
}
